// 模拟炒股数据管理云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-8g3kxnyv58f85f9b'
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, ...params } = event

  try {
    switch (action) {
      case 'getWatchlist':
        return await getWatchlist(wxContext.OPENID)
      case 'addToWatchlist':
        return await addToWatchlist(wxContext.OPENID, params)
      case 'removeFromWatchlist':
        return await removeFromWatchlist(wxContext.OPENID, params)
      case 'getRankings':
        return await getRankings()
      case 'updateRanking':
        return await updateRanking(wxContext.OPENID, params)
      default:
        return {
          success: false,
          error: 'invalid_action',
          message: '无效的操作类型'
        }
    }
  } catch (error) {
    console.error('模拟数据云函数执行失败:', error)
    return {
      success: false,
      error: 'function_failed',
      message: '操作失败，请重试',
      details: error.message
    }
  }
}

// 获取自选股
async function getWatchlist(openid) {
  try {
    // 先按_openid查询
    let result = await db.collection('simulation_watchlist').where({
      _openid: openid
    }).orderBy('addTime', 'desc').get()

    // 如果按_openid查询不到，尝试按openid字段查询
    if (result.data.length === 0) {
      result = await db.collection('simulation_watchlist').where({
        openid: openid
      }).orderBy('addTime', 'desc').get()
    }

    return {
      success: true,
      watchlist: result.data
    }
  } catch (error) {
    console.error('获取自选股失败:', error)
    throw error
  }
}

// 添加自选股
async function addToWatchlist(openid, { stockCode, stockName }) {
  try {
    // 检查是否已存在
    const existing = await db.collection('simulation_watchlist').where({
      _openid: openid,
      stockCode: stockCode
    }).get()

    if (existing.data.length > 0) {
      return {
        success: false,
        error: 'already_exists',
        message: '股票已在自选股中'
      }
    }

    // 添加到自选股
    const result = await db.collection('simulation_watchlist').add({
      data: {
        openid: openid,  // 添加openid字段
        stockCode: stockCode,
        stockName: stockName,
        addTime: db.serverDate()
      }
    })

    return {
      success: true,
      message: '添加成功',
      id: result._id
    }
  } catch (error) {
    console.error('添加自选股失败:', error)
    throw error
  }
}

// 移除自选股
async function removeFromWatchlist(openid, { stockCode }) {
  try {
    const result = await db.collection('simulation_watchlist').where({
      _openid: openid,
      stockCode: stockCode
    }).remove()

    return {
      success: true,
      message: '移除成功',
      removed: result.stats.removed
    }
  } catch (error) {
    console.error('移除自选股失败:', error)
    throw error
  }
}

// 获取排行榜
async function getRankings() {
  try {
    const result = await db.collection('simulation_rankings').orderBy('totalAssets', 'desc').limit(50).get()

    return {
      success: true,
      rankings: result.data
    }
  } catch (error) {
    console.error('获取排行榜失败:', error)
    throw error
  }
}

// 更新排行榜
async function updateRanking(openid, { nickname, totalAssets, totalProfit, profitRate }) {
  try {
    // 检查是否已存在
    const existing = await db.collection('simulation_rankings').where({
      _openid: openid
    }).get()

    if (existing.data.length > 0) {
      // 更新现有记录
      const result = await db.collection('simulation_rankings').doc(existing.data[0]._id).update({
        data: {
          nickname: nickname,
          totalAssets: totalAssets,
          totalProfit: totalProfit,
          profitRate: profitRate,
          updateTime: db.serverDate()
        }
      })

      return {
        success: true,
        message: '排行榜更新成功'
      }
    } else {
      // 创建新记录
      const result = await db.collection('simulation_rankings').add({
        data: {
          nickname: nickname,
          totalAssets: totalAssets,
          totalProfit: totalProfit,
          profitRate: profitRate,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })

      return {
        success: true,
        message: '排行榜记录创建成功',
        id: result._id
      }
    }
  } catch (error) {
    console.error('更新排行榜失败:', error)
    throw error
  }
}
